package com.alibaba.citrus.ots.sales.plan.repository;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanAuditTaskQueryRequest;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalePlanAuditTaskStatusEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalePlanAuditTaskTabTypeEnum;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanAuditTaskSDO;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.dto.CreateSalesPlanAuditTaskResponse;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.dto.LoadSalesPlanAuditTaskListRequest;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.dto.UpdateSalesPlanAuditTaskByNonIdRequest;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.dto.UpdateSalesPlanAuditTaskByNonIdResponse;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.dto.UpdateSalesPlanAuditTaskResponse;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.model.SalesPlanAuditTask;
import com.epoch.app.bcots.sales_plan.salesplanaudittask.service.SalesPlanAuditTaskService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zfd
 */
@Component
public class SalesPlanAuditTaskRepositoryImpl implements SalesPlanAuditTaskRepository{

    @Resource
    private SalesPlanAuditTaskService salesPlanAuditTaskService;

    private final static String USER_PREFIX_1 = "user:CZ_";

    private final static String USER_PREFIX_2 = "CZ_";

    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<SalesPlanAuditTaskSDO>> pageQuery(SalesPlanAuditTaskQueryRequest request) {
        LoadSalesPlanAuditTaskListRequest loadSalesPlanAuditTaskListRequest = salesPlanAuditTaskQueryRequestConverter(request);
        Result<List<SalesPlanAuditTask>> listResult = salesPlanAuditTaskService.loadSalesPlanAuditTaskList(loadSalesPlanAuditTaskListRequest);
        List<SalesPlanAuditTask> taskList = listResult.getResult();
        // step 1 数据为空
        if(CollectionUtils.isEmpty(taskList)){
            return PageResult.empty();
        }
        // step 2 结果返回
        List<SalesPlanAuditTaskSDO> salesPlanAuditTaskSDOS = taskList.stream().map(item -> {
            SalesPlanAuditTaskSDO salesPlanAuditTaskSDO = new SalesPlanAuditTaskSDO();
            BeanUtils.copyProperties(item, salesPlanAuditTaskSDO);
            salesPlanAuditTaskSDO.setPlanId(Long.toString(item.getPlanId()));
            salesPlanAuditTaskSDO.setAuditOrderId(Long.toString(item.getAuditOrderId()));
            salesPlanAuditTaskSDO.setId(Long.toString(item.getId()));
            return salesPlanAuditTaskSDO;
        }).collect(Collectors.toList());

        return PageResult.of(salesPlanAuditTaskSDOS, salesPlanAuditTaskSDOS.size());
    }

    /**
     * 参数体转换
     * @param request
     * @return
     */
    private LoadSalesPlanAuditTaskListRequest salesPlanAuditTaskQueryRequestConverter(SalesPlanAuditTaskQueryRequest request) {
        LoadSalesPlanAuditTaskListRequest loadSalesPlanAuditTaskListRequest = new LoadSalesPlanAuditTaskListRequest();
        if(request.getPlanId() != null){
            loadSalesPlanAuditTaskListRequest.setPlanId(Long.parseLong(request.getPlanId()));
        }
        if(request.getAuditOrderId() != null){
            loadSalesPlanAuditTaskListRequest.setAuditOrderId(Long.parseLong(request.getAuditOrderId()));
        }
        if(request.getType() == null){
            loadSalesPlanAuditTaskListRequest.setType(SalePlanAuditTaskTabTypeEnum.WAIT_TO_HANDLE.getCode());
        }
        // 待处理、已处理 对应查询的字段不同
        if(request.getOperatorId() != null){
            if(SalePlanAuditTaskTabTypeEnum.WAIT_TO_HANDLE.getCode().equals(request.getType())){
                loadSalesPlanAuditTaskListRequest.setStatusList(Lists.newArrayList(SalePlanAuditTaskStatusEnum.RUNNING.getCode()));
                loadSalesPlanAuditTaskListRequest.setAssignees(request.getOperatorId());
            }
            if(SalePlanAuditTaskTabTypeEnum.HAVING_HANDLE.getCode().equals(request.getType())){
                loadSalesPlanAuditTaskListRequest.setStatusList(Lists.newArrayList(SalePlanAuditTaskStatusEnum.FINISHED.getCode(),
                        SalePlanAuditTaskStatusEnum.TERMINATED.getCode(), SalePlanAuditTaskStatusEnum.REJECT.getCode(),
                        SalePlanAuditTaskStatusEnum.REVOKE.getCode()));
                loadSalesPlanAuditTaskListRequest.setPrincipal(request.getOperatorId());
            }
        }

        if(request.getPlanStartTime() != null){
            loadSalesPlanAuditTaskListRequest.setPlanStartTime(DateUtils.dateToStamp(request.getPlanStartTime()));
        }
        if(request.getPlanEndTime() != null){
            loadSalesPlanAuditTaskListRequest.setPlanEndTime(DateUtils.dateToStamp(request.getPlanEndTime()));
        }
        if (!CollectionUtils.isEmpty(request.getAuditOrderIdList())) {
            loadSalesPlanAuditTaskListRequest.setAuditOrderIdList(request.getAuditOrderIdList().stream().map(Long::parseLong).collect(Collectors.toList()));
        }
        loadSalesPlanAuditTaskListRequest.setStart(request.getStart());
        loadSalesPlanAuditTaskListRequest.setLimit(request.getLimit());
        loadSalesPlanAuditTaskListRequest.setTaskCode(request.getTaskCode());
        loadSalesPlanAuditTaskListRequest.setTaskCodeList(request.getTaskCodeList());
        loadSalesPlanAuditTaskListRequest.setDir("gmtCreate");
        loadSalesPlanAuditTaskListRequest.setAsc(true);
        return loadSalesPlanAuditTaskListRequest;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public String save(SalesPlanAuditTaskSDO salesPlanAuditTaskSDO) {
        SalesPlanAuditTask salesPlanAuditTask = new SalesPlanAuditTask();
        BeanUtils.copyProperties(salesPlanAuditTaskSDO, salesPlanAuditTask);
        refreshSalesPlanAuditTask(salesPlanAuditTask);
        salesPlanAuditTask.setAuditOrderId(Optional.ofNullable(salesPlanAuditTaskSDO.getAuditOrderId()).map(s -> Long.parseLong(salesPlanAuditTaskSDO.getAuditOrderId())).orElse(null));
        salesPlanAuditTask.setPlanId(Optional.ofNullable(salesPlanAuditTaskSDO.getPlanId()).map(s -> Long.parseLong(salesPlanAuditTaskSDO.getPlanId())).orElse(null));
        CreateSalesPlanAuditTaskResponse salesPlanAuditTaskResponse = salesPlanAuditTaskService.createSalesPlanAuditTask(salesPlanAuditTask);
        return salesPlanAuditTaskResponse.getLastInsertId();
    }

    private void refreshSalesPlanAuditTask(SalesPlanAuditTask salesPlanAuditTask) {
        salesPlanAuditTask.setAuditInitiatorId(StringUtils.replace(salesPlanAuditTask.getAuditInitiatorId(), USER_PREFIX_2,""));
        salesPlanAuditTask.setCreatorId(StringUtils.replace(salesPlanAuditTask.getCreatorId(), USER_PREFIX_2,""));
        salesPlanAuditTask.setModifierId(StringUtils.replace(salesPlanAuditTask.getModifierId(), USER_PREFIX_2,""));

        JSONArray jsonArray = JSON.parseArray(salesPlanAuditTask.getAssignees());
        StringBuilder stringBuilder = new StringBuilder();
        jsonArray.forEach(o -> stringBuilder.append(StringUtils.replace(String.valueOf(o), USER_PREFIX_1,"")).append(","));
        salesPlanAuditTask.setAssignees(stringBuilder.toString());
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean edit(SalesPlanAuditTaskSDO salesPlanAuditTaskSDO) {
        SalesPlanAuditTask salesPlanAuditTask = new SalesPlanAuditTask();
        BeanUtils.copyProperties(salesPlanAuditTaskSDO, salesPlanAuditTask);
        salesPlanAuditTask.setId(Optional.ofNullable(salesPlanAuditTaskSDO.getId()).map(id -> Long.parseLong(salesPlanAuditTaskSDO.getId())).orElse(null));
        UpdateSalesPlanAuditTaskResponse updateSalesPlanAuditTaskResponse = salesPlanAuditTaskService.updateSalesPlanAuditTask(salesPlanAuditTask);
        return updateSalesPlanAuditTaskResponse.getCount() > 0;
    }

    /**
     * 更新审核任务
     *
     * @param salesPlanAuditTaskSDO
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean updateSalesPlanAuditTaskByNonId(SalesPlanAuditTaskSDO salesPlanAuditTaskSDO) {
        UpdateSalesPlanAuditTaskByNonIdRequest request = new UpdateSalesPlanAuditTaskByNonIdRequest();
        BeanUtils.copyProperties(salesPlanAuditTaskSDO, request);
        refreshUpdateSalesPlanAuditTaskByNonIdRequest(request);
        UpdateSalesPlanAuditTaskByNonIdResponse response = salesPlanAuditTaskService.updateSalesPlanAuditTaskByNonId(request);
        return response.getCount() > 0;
    }

    private void refreshUpdateSalesPlanAuditTaskByNonIdRequest(UpdateSalesPlanAuditTaskByNonIdRequest request) {
        if (null != request.getPrincipal()) {
            request.setPrincipal(StringUtils.replace(request.getPrincipal(), USER_PREFIX_2,""));
        }
    }
}
